import os
from pathlib import Path


def update_file(file, old_str, new_str):
    """
    替换文件中的字符串
    :param file:文件名
    :param old_str:就字符串
    :param new_str:新字符串
    :return:
    """
    file_data = ""
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str, new_str)
            file_data += line
    with open(file, "w", encoding="utf-8") as f:
        f.write(file_data)


def updates_file(replace_content_dict):
    """
    替换文件中的字符串
    :param replace_content_dict: 待替换内容的字典，注意替换内容需无顺序和冲突
    :return:
    """
    path1 = Path(__file__).resolve()
    path2 = os.path.dirname(path1)
    path3 = os.path.dirname(path2)
    path4 = path3 + "/rsync_conf_files/settings.py"

    file_data = ""
    with open(path4, "r", encoding="utf-8") as f:
        for line in f:
            for old_content, new_content in replace_content_dict.items():
                # print(old_content, " ", new_content)
                if old_content in line:
                    line = line.replace(old_content, new_content)
            file_data += line
    with open(path4, "w", encoding="utf-8") as f:
        f.write(file_data)


if __name__ == "__main__":
    # # 修改ip
    # update_file(path4,"x.x.x.x" , "x.x.x.x")
    # to_replace_content = {
    #     "x.x.x.x": "x.x.x.x",
    #     "x.x.x.x": "x.x.x.x",
    #     "/root/data1/": "/data",
    # }
    # updates_file(to_replace_content)
    pass
